// pages/withdraw/withdraw.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    outOfBound:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      inputValue: "",
      navH: app.globalData.navHeight,
    });

    wx.request({
      url: app.globalData.url + 'getUserByUserId?userId=' + wx.getStorageSync("userId"),
      method:"get",
      success:function(res){
        that.setData({
          balance: res.data.data.balance,
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  getInputValue:function(e){
    var that = this;
    var balance = parseInt(that.data.balance);
    if(e.detail.value > balance){
      that.setData({
        outOfBound:true,
        money: e.detail.value,
      });
    } else {
      that.setData({
        outOfBound: false,
        money: e.detail.value,
      });
    }
  },

  withdraw:function(e){
    var that = this;
    if(that.data.outOfBound || that.data.money == undefined || that.data.money <= 0){
      wx.showToast({
        title: '提现金额不正确!',
        icon:"none"
      })
      
    } else {
      //提现
      var money = that.data.money;
      var balance = that.data.balance;
      //先将余额扣除，防止用户连续点击提现
      that.setData({
        balance: balance - money,
      });
      wx.request({
        url: app.globalData.url + 'addDiscountRecord',
        method:"post",
        header:{
          'content-type': 'application/x-www-form-urlencoded'
        },
        data:{
          userId:wx.getStorageSync("userId"),
          withdrawBalance: money,
          poundage:0.001,
          weChat:null,
        },
        success:function(res){
          if(res.data.result == 1){
            wx.showToast({
              title: '申请成功，等待后台审核！',
              icon:"success",
            });
            setTimeout(function(){
              that.onLoad();
            },1500);
          } else {
            wx.showToast({
              title: res.data.errmsg,
              icon:"none",
            })
          }
        }
      })
    }
  },

  navBack: function () {
    wx.navigateBack({

    })
  }
})